"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 服务端工具
Case Name   : 安装场景下执行检查修复支持设置的Abnormal项
Create At   : 2021/10/11
Owner       : opentestcase002
Description :
     安装场景下执行检查修复支持设置的Abnormal项：gs_check -e install --set
Expect      :
     检查完成
History     :
    modified by opentestcase012 at 2022-11-9:优化用例,添加ip_local_port_range的备份和恢复,
        修改os.popen为get_sh_result
"""

import os
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.dbuser_node = Node('dbuser')
        self.root_node = Node('default')
        self.clear_path = os.path.join(
            os.path.dirname(macro.DB_INSTANCE_PATH), 'tool', 'script',
            'gspylib', 'inspection', 'output', 'CheckReport*')
        self.Constant = Constant()
        self.send_var = 'N'
        self.comm = Common()
        primary_sh = CommonSH('PrimaryDbUser')
        self.nodes_range = {Node('PrimaryRoot'): ''}
        if primary_sh.get_node_num() == 3:
            self.nodes_range = {Node('PrimaryRoot'): '',
                                Node('Standby1Root'): '',
                                Node('Standby2Root'): ''}

        self.log.info("======查看系统端口范围======")
        self.grep_cmd = 'sysctl -e net.ipv4.ip_local_port_range;'
        self.log.info(self.grep_cmd)
        for node in self.nodes_range.keys():
            portrange = self.comm.get_sh_result(node, self.grep_cmd)
            self.nodes_range[node] = portrange

    def test_server_tools1(self):
        text = '------step1:安装场景下执行检查修复支持设置的Abnormal项;expect:检查完成-------'
        self.log.info(text)
        check_cmd = f'''source {macro.DB_ENV_PATH}
                   expect <<EOF
                   set timeout 400
                   spawn gs_check -e install --set
                   expect "*):"
                   send "{self.send_var}\\n"
                   expect "*]:"
                   send "{self.root_node.ssh_user}\\n"
                   expect "*]:"
                   send "{self.root_node.ssh_password}\\n"
                   expect eof\n''' + '''EOF'''
        self.log.info(check_cmd)
        str_res = self.comm.get_sh_result(self.dbuser_node, check_cmd)
        flag = (self.Constant.GS_CHECK_SUCCESS_MSG2[0] in str_res or
                self.Constant.GS_CHECK_SUCCESS_MSG2[1] in str_res) and \
               self.Constant.GS_CHECK_SUCCESS_MSG2[2] in str_res
        self.assertTrue(flag, '执行失败:' + text)

    def tearDown(self):
        text = '----------清理环境----------'
        self.log.info(text)
        clear_cmd = f'rm -rf {self.clear_path};'
        self.log.info(clear_cmd)
        clear_msg = self.root_node.sh(clear_cmd).result()
        self.log.info(clear_msg)

        self.log.info("-----恢复系统端口范围-----")
        range_list = []
        sysctl_path = os.path.join('/', 'etc', 'sysctl.conf')
        for node, value in self.nodes_range.items():
            cat_cmd = f'cat {sysctl_path} | grep "ip_local_port_range";'
            self.log.info(cat_cmd)
            portrange = self.comm.get_sh_result(node, cat_cmd)
            sed_cmd = f"sed -i 's#{portrange}#{value}#g' {sysctl_path};" \
                f"sysctl -p {sysctl_path};"
            self.log.info(sed_cmd)
            self.comm.get_sh_result(node, sed_cmd)
            portrange = self.comm.get_sh_result(node, self.grep_cmd)
            range_list.append(portrange)

        self.assertEqual('', clear_msg, '执行失败:' + text)
        self.assertEqual(range_list, list(self.nodes_range.values()),
                         '执行失败:' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
